package com.zookeeper.ref.election;

/**
 * Author: dong peng
 * Date: 2018/1/23
 * Time: 11:50
 */

import org.I0Itec.zkclient.ZkClient;
import org.I0Itec.zkclient.serialize.SerializableSerializer;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

/**
 * 调度器
 */
public class LeaderSelectorZkClient {
    //启动的服务个数
    private static final int        CLIENT_QTY = 10;
    //zookeeper服务器的地址
    private static final String     ZOOKEEPER_SERVER = "127.0.0.1:2181,127.0.0.1:2182,127.0.0.1:2183";


    public static void main(String[] args) throws Exception {
        //保存所有zkClient的列表
        List<ZkClient> clients = new ArrayList<ZkClient>();
        //保存所有服务的列表
        List<WorkServer>  workServers = new ArrayList<WorkServer>();

        try {
            for ( int i = 0; i < CLIENT_QTY; ++i ) { // 模拟创建10个服务器并启动
                //创建zkClient
                ZkClient client = new ZkClient(ZOOKEEPER_SERVER, 5000, 5000, new SerializableSerializer());
                clients.add(client);
                //创建serverData
                RunningData runningData = new RunningData();
                runningData.setCid(Long.valueOf(i));
                runningData.setName("Client #" + i);
                //创建服务
                WorkServer  workServer = new WorkServer(runningData);
                workServer.setZkClient(client);

                workServers.add(workServer);
                workServer.start();
            }

            System.out.println("敲#退出!输入0-9停止指定服务");
            String input = new BufferedReader(new InputStreamReader(System.in)).readLine();
            while (!"#".equals(input)) {
                int index = Integer.parseInt(input);
                WorkServer wk = workServers.get(index);
                wk.stop();
                input = new BufferedReader(new InputStreamReader(System.in)).readLine();
            }

        } finally {

            System.out.println("Shutting down...");

            for ( WorkServer workServer : workServers ) {
                try {
                    workServer.stop();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            for ( ZkClient client : clients ) {
                try {
                    client.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
